package com.backflash.client;

import com.backflash.client.screens.ThreadScreen;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

public class SingleThread extends Composite {
	
	Topic t = new Topic();
	Integer i = 0;
	
	public SingleThread(Topic result, Integer i) {
		t = result;
		this.i = i;
		
		VerticalPanel singleThreadPanel = new VerticalPanel();
		HorizontalPanel userDateDeletePanel = new HorizontalPanel();
		
		TextArea messageTextArea = new TextArea();
		Label writtenByPanel = new Label("Written by: " + result.getMessages().get(i).getUser());
		Label dateLabel = new Label(" Date: " + result.getMessages().get(i).time);
		Button deleteMessageButton = new Button("Delete");
		deleteMessageButton.setStyleName("deleteButton");
		deleteMessageButton.setSize("60px", "20px");
		
		messageTextArea.setStyleName("messageTextArea");
		messageTextArea.setVisibleLines(10);
		messageTextArea.setText(result.getMessages().get(i).getMessage());
		
		userDateDeletePanel.addStyleName("userDatePanel");
		userDateDeletePanel.add(writtenByPanel);
		userDateDeletePanel.add(dateLabel);
		userDateDeletePanel.add(deleteMessageButton);
		
		dateLabel.setSize("100%", "100%");
		
		writtenByPanel.setSize("100%", "100%");
		
		
		singleThreadPanel.add(userDateDeletePanel);
		singleThreadPanel.add(messageTextArea);
		
		initWidget(singleThreadPanel);
		
		//Listen for mouse events on the send button
		deleteMessageButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				deleteMessage();
			}
		});
	}
	private BackFlashServiceAsync getService() {
		BackFlashServiceAsync svc = (BackFlashServiceAsync) GWT.create(BackFlashService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) svc;
		endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "BackFlashService");

		return svc;
	}
	
	private void deleteMessage(){
		//Async call to the server
		AsyncCallback<Topic> callback = new AsyncCallback<Topic>() {
			@Override
			public void onSuccess(Topic result) {
				//Laddar om sidan ThreadScreen
				BackFlash.get().setThreadScreen(t.getHeading());
			}
			@Override
			public void onFailure(Throwable ex) {
			}
		};
		getService().deleteMessage(t.getIndex(), t.getMessages().get(i), callback);
	}

}
